<template>
  <view class="message-item">
    <!-- 消息分割线 -->
    <view
      class="time-divider flex items-center justify-center my-30rpx"
      v-if="
        msgInfo.type == enums.MESSAGE_TYPE.RECALL || msgInfo.type == enums.MESSAGE_TYPE.TIP_TEXT
      "
    >
      <text class="time text-22rpx text-[#999] bg-[#f5f5f5] px-16rpx">
        {{ msgInfo.content }}
      </text>
    </view>
    <!-- 时间分割线 -->
    <view
      class="time-divider flex items-center justify-center my-30rpx"
      v-if="msgInfo.type == enums.MESSAGE_TYPE.TIP_TIME"
    >
      <text class="time text-22rpx text-[#999] bg-[#f5f5f5] px-16rpx">
        {{ toTimeText(msgInfo.sendTime, false) }}
      </text>
    </view>

    <!-- 消息内容 -->
    <view :class="['flex', msgInfo.selfSend ? 'justify-end' : '']" v-if="handleNormal">
      <!-- 左侧头像 -->
      <wd-img
        class="avatar-image w-78rpx h-78rpx rounded-full mr-12rpx"
        :src="headImage ? headImage : 'null'"
        round
        v-if="!msgInfo.selfSend"
      >
        <template #error>
          <view class="error-wrap">{{ msgInfo.sendNickName }}</view>
        </template>
      </wd-img>

      <view class="flex-1" :class="[msgInfo.selfSend ? 'text-right' : '']">
        <!-- 用户名 -->
        <text v-if="!msgInfo.selfSend" class="text-24rpx text-[#999] mb-12rpx block">
          {{ msgInfo.sendNickName }}
        </text>

        <!-- 消息气泡 -->
        <view
          class="message-bubble"
          :class="[msgInfo.selfSend ? 'self' : '', msgInfo.type != '1' ? 'bg-[#3670F7]' : '']"
        >
          <!-- 文本消息 -->
          <text
            v-if="msgInfo.type == '0'"
            class="text-message"
            :class="[msgInfo.selfSend ? 'text-white' : 'text-[#333]']"
          >
            {{ msgInfo.content }}
          </text>

          <!-- 图片消息 -->
          <image
            class="send-image"
            v-else-if="msgInfo.type == '1'"
            :src="JSON.parse(msgInfo.content).thumbUrl"
            mode="widthFix"
            @tap="previewImage(JSON.parse(msgInfo.content).thumbUrl)"
            @load="onImageLoad"
          />

          <view
            class="flex items-center"
            @click="onPlayAudio()"
            v-if="msgInfo.type == enums.MESSAGE_TYPE.AUDIO"
          >
            <template v-if="!state.voicePlaying && !msgInfo.selfSend">
              <image
                class="w-32rpx h-32rpx mr-24rpx"
                src="/static/images/voice-user.png"
                mode="scaleToFill"
              />
            </template>
            <template v-if="state.voicePlaying && !msgInfo.selfSend">
              <image
                class="w-32rpx h-32rpx mr-24rpx"
                src="/static/images/yyy.gif"
                mode="scaleToFill"
              />
            </template>
            <view class="chat-audio-text">{{ JSON.parse(msgInfo.content).duration + '"' }}</view>
            <template v-if="msgInfo.selfSend && !state.voicePlaying">
              <image
                class="w-32rpx h-32rpx ml-24rpx"
                src="/static/images/yyz.png"
                mode="scaleToFill"
              />
            </template>
            <template v-if="msgInfo.selfSend && state.voicePlaying">
              <image
                class="w-32rpx h-32rpx ml-24rpx"
                src="/static/images/yyz.gif"
                mode="scaleToFill"
              />
            </template>
          </view>

          <!-- 视频消息 -->
          <video v-else-if="msgInfo.type == 'video'" :src="msgInfo.content" object-fit="cover" />
        </view>
      </view>

      <!-- 右侧头像 -->
      <wd-img
        class="w-78rpx h-78rpx rounded-full ml-20rpx"
        :src="headImage ? headImage : 'null'"
        round
        v-if="msgInfo.selfSend"
      >
        <template #error>
          <view class="error-wrap">{{ msgInfo.sendNickName }}</view>
        </template>
      </wd-img>
    </view>
  </view>
</template>

<script setup lang="ts">
import * as enums from '@/utils/enums'
import { toTimeText } from '@/common/date'
import { isNormal, isAction } from '@/utils/messageType'
const innerAudioContext = uni.createInnerAudioContext()

// Props定义
const props = defineProps({
  headImage: {
    type: String,
    required: false,
  },
  showName: {
    type: String,
    required: true,
  },
  msgInfo: {
    type: Object,
    required: true,
  },
  groupMembers: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
})
const state = reactive({
  audioPlayState: 'STOP',
  innerAudioContext: null,
  voicePlaying: false,
})
onMounted(() => {
  innerAudioContext.onStop((res) => {
    console.log('音频停止事件=======')
    state.voicePlaying = false
  })
  innerAudioContext.onEnded((res) => {
    console.log('音频自然播放结束事件=====')
    state.voicePlaying = false
  })
  innerAudioContext.onError((res) => {
    console.log('音频播放错误事件========')
    state.voicePlaying = false
  })
  innerAudioContext.onPlay((res) => {
    console.log('音频播放事件========')
    state.voicePlaying = true
  })
})

const handleNormal = computed(() => {
  const type = props.msgInfo.type
  return isNormal(type) || isAction(type)
})

// Emits定义
const emit = defineEmits(['longPressHead', 'copy', 'recall', 'delete', 'download'])
function previewImage(content) {
  uni.previewImage({
    urls: [content],
  })
}
function onImageLoad() {}
function onPlayAudio() {
  if (state.voicePlaying) {
    state.voicePlaying = false
    innerAudioContext.stop()
    return
  }
  innerAudioContext.stop()
  const url = JSON.parse(props.msgInfo.content).url
  innerAudioContext.src = url?.url || url
  innerAudioContext.play()
}
</script>

<style lang="scss" scoped>
// 优化用户名显示
.user-name {
  padding-left: 8rpx;
  margin-bottom: 8rpx;
  font-size: 24rpx;
  color: #999;
}

.message-bubble {
  position: relative;
  display: inline-block;
  max-width: 520rpx;
  padding: 20rpx 24rpx;
  word-break: break-all;
  border-radius: 12rpx;

  // 优化气泡样式
  &:not(.self) {
    margin-right: 180rpx;
    background-color: #fff;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

    &::before {
      position: absolute;
      top: 24rpx;
      left: -16rpx;
      width: 0;
      height: 0;
      content: '';
      border: 8rpx solid transparent;
      border-right-color: #fff;
    }
  }

  &.self {
    margin-left: 180rpx;
    box-shadow: 0 2rpx 8rpx rgba(7, 193, 96, 0.2);

    &::before {
      position: absolute;
      top: 24rpx;
      right: -16rpx;
      width: 0;
      height: 0;
      content: '';
      border: 8rpx solid transparent;
      border-left-color: #3670f7;
    }
  }

  // 优化图片和视频显示
  image,
  video {
    display: block;
    max-width: 400rpx;
    overflow: hidden;
    border-radius: 8rpx;
  }

  // 优化文本消息
  .text-message {
    min-width: 40rpx;
    max-width: 100%;
    font-size: 32rpx;
    line-height: 44rpx;
  }
}

// 优化时间显示
.time-divider {
  margin: 24rpx 0;

  .time {
    padding: 8rpx 16rpx;
    font-size: 24rpx;
    color: #999;
    border-radius: 24rpx;
  }
}

// 优化头像样式
.avatar-image {
  flex-shrink: 0;
  object-fit: cover;
  border: none;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}
.error-wrap {
  width: 78rpx;
  height: 78rpx;
  padding: 0 2rpx;
  overflow: hidden;
  line-height: 78rpx;
  color: white;
  text-align: center;
  background: linear-gradient(270deg, #7ea1f1 3%, #3670f7 96%);
}
.send-image {
  min-width: 200rpx !important;
  max-width: 320rpx !important;
  border-radius: 4px;
}
</style>
